var key = getCookie("key");
var rcb_pay, pd_pay, payment_code;
function toPay(a, e, p) {
	// 显示加载中
	window.layerIndex = layer.open({
		type: 2,
		shadeClose: false
	});
    $.ajax({
        type: "post",
        url: ApiUrl + "/" + e + "/" + p+".html",
        data: {
            key: key,
            pay_sn: a
        },
        dataType: "json",
        success: function(p) {
	        layer.close(window.layerIndex);
            checkLogin(p.login);
            if (p.code != 10000) {
                layer.open({content: p.message, btn: '我知道了'});
                return false
            }
            $("#onlineTotal").html(p.result.pay_info.pay_amount);
            if (!p.result.pay_info.member_paypwd) {
                $("#wrapperPaymentPassword").find(".input-box-help").show();
            }
            var s = false;
            if (parseFloat(p.result.pay_info.payed_amount) <= 0) {
                if (parseFloat(p.result.pay_info.member_available_pd) == 0 && parseFloat(p.result.pay_info.member_available_rcb) == 0) {
                    $("#internalPay").hide()
                } else {
                    $("#internalPay").show();
                    if (parseFloat(p.result.pay_info.member_available_rcb) != 0) {
                        $("#wrapperUseRCBpay").show();
                        $("#availableRcBalance").html(parseFloat(p.result.pay_info.member_available_rcb).toFixed(2))
                    } else {
                        $("#wrapperUseRCBpay").hide()
                    }
                    if (parseFloat(p.result.pay_info.member_available_pd) != 0) {
                        $("#wrapperUsePDpy").show();
                        $("#availablePredeposit").html(parseFloat(p.result.pay_info.member_available_pd).toFixed(2))
                    } else {
                        $("#wrapperUsePDpy").hide()
                    }
                }
            } else {
                $("#internalPay").hide()
            }
            
            rcb_pay = 0;
            $("#useRCBpay").unbind().click(function() {
                if ($(this).prop("checked")) {
                    s = true;
                    $("#wrapperPaymentPassword").show();
                    rcb_pay = 1
                } else {
                    if (pd_pay == 1) {
                        s = true;
                        $("#wrapperPaymentPassword").show()
                    } else {
                        s = false;
                        $("#wrapperPaymentPassword").hide()
                    }
                    rcb_pay = 0
                }
            });
            pd_pay = 0;
			
			$("body").on('tap','#wrapperUsePDpy .power',function () {
				if(!$("#wrapperUsePDpy").find('label').hasClass("checked")) {
					$("#wrapperUsePDpy").find('label').addClass("checked");
					s = true;
					$("#wrapperPaymentPassword").show();
					pd_pay = 1
				} else {
					$("#wrapperUsePDpy").find('label').removeClass("checked");
					if (rcb_pay == 1) {
					    s = true;
					    $("#wrapperPaymentPassword").show()
					} else {
					    s = false;
					    $("#wrapperPaymentPassword").hide()
					}
					pd_pay = 0
				}
			});
			
            // $("#usePDpy").unbind().click(function() {
            //     if ($(this).prop("checked")) {
            //         s = true;
            //         $("#wrapperPaymentPassword").show();
            //         pd_pay = 1
            //     } else {
            //         if (rcb_pay == 1) {
            //             s = true;
            //             $("#wrapperPaymentPassword").show()
            //         } else {
            //             s = false;
            //             $("#wrapperPaymentPassword").hide()
            //         }
            //         pd_pay = 0
            //     }
            // });
            payment_code = "";
            if (!$.isEmptyObject(p.result.pay_info.payment_list)) {
                var t = false;
                var r = false;
                var n = navigator.userAgent.match(/MicroMessenger\/(\d+)\./);
                if (parseInt(n && n[1] || 0) >= 5) {
                    t = true
                } else {
                    r = true
                }
                for (var o = 0; o < p.result.pay_info.payment_list.length; o++) {
                    var i = p.result.pay_info.payment_list[o].payment_code;
                    var payment = p.result.pay_info.payment_list[o];

                    // 默认第一种支付方式
                    if(o === 0) {
                        payment_code = i;
                    }

                    // 境外订单非微信内只支持APP支付
                    if(payment.payment_platform === 'app' && typeof plus === 'undefined') {
                        mui.toast('进口商品仅支持微信内或APP内支付');
                        return;
                    }

                    $("#" + i).parents("label").show();
                    if (i == "alipay_h5" && r) {
                        if (payment_code == "") {
                            payment_code = i;
                        }
                    }
                    if (i == "wxpay_jsapi" && t) {
                        if (payment_code == "") {
                            payment_code = i;
                        }
                    }
                    if (i == "wxpay_h5" && t) {
                        if (payment_code == "") {
                            payment_code = i;
                        }
                    }
                    if (i == "wxpay_minipro" && t) {
                        if (payment_code == "") {
                            payment_code = i;
                        }
                    }
                    if (i == "allinpay_h5" && t) {
                        if (payment_code == "") {
                            payment_code = i;
                        }
                    }
                }
            }

            if(payment_code) $("#" + payment_code).attr("checked", true).parents("label").addClass("checked")

            // 显示支付弹窗
            $.animationUp({
                valve: "",
                scroll: ""
            });
            // 去支付
            $("#toPay").unbind().click(function() {
                if (payment_code == "") {
                    layer.open({content: '请选择支付方式',skin: 'msg',time: 2});
                    return false
                }
                if (s) {
                    if ($("#paymentPassword").val() == "") {
                        layer.open({content: '请填写支付密码',skin: 'msg',time: 2});
                        return false
                    }
                    $.ajax({
                        type: "post",
                        url: ApiUrl + "/Memberbuy/check_pd_pwd.html",
                        dataType: "json",
                        data: {
                            key: key,
                            password: $("#paymentPassword").val()
                        },
                        success: function(p) {
                            if (p.code != 10000) {
                                layer.open({content: p.message,skin: 'msg',time: 3});
                                return false;
                            }else{
								// goToPayment(a, e == "memberbuy" ? "pay_new": "vr_pay_new");
                                layer.open({content:'支付密码验证成功！'});
                            }
                            setTimeout(function () {
                                goToPayment(a, e == "memberbuy" ? "pay_new": "vr_pay_new");
                            }, 2000);
                        }
                    })
                } else {
                    goToPayment(a, e == "memberbuy" ? "pay_new": "vr_pay_new")
                }
            })
        }
    })
}

// 选择支付方式
$('body').on('tap', '#pay-sel > label', function () {
    payment_code = $(this).find('input').attr('id');
    $(this).siblings().removeClass('checked');
    $(this).addClass("checked");
    return false;
});

// mui 原生支付调起
function goToPlusPayment(pay_sn, params) {
    window.windowShowReload = true;     // app 中页面重新显示时刷新
    // 扩展API加载完毕，现在可以正常调用扩展API
    plus.payment.getChannels(function(channels){
        var channel = null;
        channels.forEach(function (item) {
            if(
                ((payment_code === 'wxpay_app' || payment_code === 'wxpay_external_app' ) && item.id === 'wxpay')
                || (payment_code === 'alipay_app' && item.id === 'alipay')
            ) {
                channel = item;
            }
        });

        if(!channel) {m
            mui.alert("获取支付通道列表失败："+e.message, '支付提示', '确定', function () {
                pageChange('../public/pay_jump.html', {pay_sn: pay_sn});
            }, 'div');
            return;
        }

        // 支付
        plus.payment.request(channel, params, function(result){
            pageChange('../public/pay_jump.html', {pay_sn: pay_sn});
        },function(error){
            var msg = (error.code == -100) ? "支付已取消" : "支付失败[" + error.code + ']:'+ error.message;

            mui.alert(msg, '支付提示', '确定', function () {
                pageChange('../public/pay_jump.html', {pay_sn: pay_sn});
            }, 'div');
        });
    }, function(e){
        mui.alert("获取支付通道列表失败："+e.message, '支付提示', '确定', function () {
            pageChange('../public/pay_jump.html', {pay_sn: pay_sn});
        }, 'div');
    });
}

// 调起支付
function goToPayment(a, e) {
    if(payment_code === "wxpay_minipro" && pd_pay !== 1) {
        wx.miniProgram.redirectTo({url: "../pay/pay?action=" + e + "&key=" + key + "&pay_sn=" + a + "&password=" + $("#paymentPassword").val() + "&rcb_pay=" + rcb_pay + "&pd_pay=" + pd_pay + "&payment_code=" + payment_code});
    } else if ((payment_code === 'wxpay_app' || payment_code === 'wxpay_external_app') && pd_pay !== 1) {
        // 微信 app 支付
        baseApi.post(
            'Memberpayment/' + e,
            {
                pay_sn: a,
                password: $("#paymentPassword").val(),
                rcb_pay: rcb_pay,
                pd_pay: pd_pay,
                payment_code: payment_code
            },
            function (result) {
                if(result === 'pay_success'){
                    pageChange('../public/pay_jump.html?pay_sn=' + a, {title: '支付结果'});
                } else {
                    goToPlusPayment(a, result);
                }
            }
        );
    }else{
        var url = http+SiteDomain + "/?s=mobile/Memberpayment/" + e + "/key/" + key + "/pay_sn/" + a + "/password/" + $("#paymentPassword").val() + "/rcb_pay/" + rcb_pay + "/pd_pay/" + pd_pay + "/payment_code/" + payment_code + "/client_type/" + getClientType();
        window.windowShowReload = true;     // app 中页面重新显示时刷新
        pageChange(url, {
            title: '订单支付',
            full_screen: 1
        });
    }
    
}

/*同调调用可用支付相关显示方式*/
$(function() {
    var e = getCookie("key");
    if (!e) {
        pageChange("../member/login_mobile.html");
        return
    }
    var paysn = getQueryString('paysn');
    $.ajax({
        type: 'post',
        url: ApiUrl + "/Memberpayment/payment_list.html",
        data: {key: e},
        dataType: 'json',
        success: function(result) {
            if (result.code == 10000) {
                var data = result.result;
                data.ApiUrl = ApiUrl;
                data.key = e;
                var html = template('pay-sel-tmpl', data);
                $("#pay-sel").html(html);
            }
            else {
                alert(result.message);
                pageChange("..../member/member.html");
            }
        }
    });
});